<template>
    <div class="neo4jMain">
      <div class="addContent">
        <el-form :inline="true" :model="formInline" :rules="rules" ref="neo4jform">
          <el-form-item label="人物名称" prop="startNode">
            <el-input v-model="formInline.startNode" placeholder="请输入关键词"></el-input>
          </el-form-item>
          <!-- <el-form-item label="关系名称" prop="relationName">
            <el-input v-model="formInline.relationName" placeholder="请输入关系名称"></el-input>
          </el-form-item> -->
          <!-- <el-form-item label="结束节点名称" prop="endNode">
            <el-input v-model="formInline.endNode" placeholder="请输入结束节点名称"></el-input>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="search()">检索</el-button>
  <!--          <el-button type="primary" @click="onDelete">清空表</el-button>-->
          </el-form-item>
        </el-form>
      </div>
      <div class="echarts" style=" height:850px" ref="echarts">
      </div>
    </div>
  </template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
const animationDuration = 6000
export default {
  data() {
    return {
        rules: {
        startNode: [{required: true, trigger: 'blur'}],
        endNode: [{required: true, trigger: 'blur'}],
        relationName: [{required: true, trigger: 'blur'}]
      },
      chart: null,
      protocol: 'bolt',
      host: '172.16.218.125',
      port: 7687,
      username: 'neo4j',
      password: '123456',
      nodelist:[],
      formInline: {
        startNode: '王夫人',
        endNode: '',
        relationName: ''
      },
      echartsData: [],
      nodesRelation: []
 
    }
  },
  
  mounted() {
    // this.$nextTick(() => {
    //   this.initChart()
    // })
    this.query(this.formInline.startNode);
  
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
        initEcharts() {
      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.init(this.$refs.echarts)
      console.log("echartsData",this.echartsData)
      // 绘制图表
      myChart.setOption({
        title: {
          text: 'Neo4j 图谱关系'
        },
        tooltip: {},
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            type: 'graph',
            layout: 'force',
            force: {
                repulsion: 1500,
                edgeLength: 120,
                layoutAnimation: true,
            },
            symbolSize: 70,
            roam: true,
            label: {
                normal: {
                    show: true,
                    position: 'inside',
                    color: '#FFF',
                },
            },
            itemStyle: {
                normal: {
                    borderColor: '#29ACFC',
                    borderWidth: 2,
                    shadowColor: '#29ACFC',
                    color: '#29ACFC',
                    curveness: 0.08,
                },
            },
            edgeSymbol: ['none', 'arrow'],
            edgeSymbolSize: [4, 10],
            edgeLabel: {
              fontSize: 20
            },
            data: this.echartsData,
            // links: [],
            links: this.nodesRelation,
            lineStyle: {
              opacity: 0.9,
              width: 2,
              curveness: 0
            }
          }
        ]
      });
    },
        query(name) {
      this.connect();
      const session = this.$neo4j.getSession();
      let cypher = `match p=(n)-[]->(m)   return  p `;
      if(name){
         cypher = `match p=(n)-[]->(m) where n.name='${name}'  return  p `;
      }
     
      session.run(cypher).then(res => {
        console.log("555",res)
        let records = res.records;
        let nodes = new Set();
        this.nodesRelation = [];
        for (let i = 0; i < records.length; i++) {
          nodes.add({'name': records[i]._fields[0].segments[0].start.properties.name,'info': records[i]._fields[0].segments[0].start.properties.info});
          nodes.add({'name':records[i]._fields[0].segments[0].end.properties.name,'info': records[i]._fields[0].segments[0].end.properties.info});
          this.nodesRelation.push({
            source: records[i]._fields[0].segments[0].start.properties.name,
            target: records[i]._fields[0].segments[0].end.properties.name,
            lineStyle: {
              curveness: 0
            },
            label: {
              show: true,
              formatter: function() {
                return records[i]._fields[0].segments[0].relationship.type
              }
            }
          });
        }

        console.log("this.nodesRelation",this.nodesRelation)
        let curveness = [0, 0.4, -0.4, 0.3, -0.3, 0.2, -0.2, 0.1, -0.1];
        for (let j = 0; j < this.nodesRelation.length; j++) {
          let repeatNumber = 0;
          for (let s = j+1; s < this.nodesRelation.length; s++) {
            let r1 = this.nodesRelation[j];
            let r2 = this.nodesRelation[s];
            if (r1.source === r2.source &&
                r1.target === r2.target) {
              repeatNumber =  repeatNumber + 1;
            }
            else if (r1.target === r2.source &&
                r1.source === r2.target) {
              repeatNumber =  repeatNumber + 1;
            }
          }
          this.nodesRelation[j].repeatNumber = repeatNumber;
        }
        for (let j = 0; j < this.nodesRelation.length; j++) {
          console.log(this.nodesRelation[j].repeatNumber);
          this.nodesRelation[j].lineStyle.curveness = curveness[this.nodesRelation[j].repeatNumber];
        }
         var  bb=[]
         bb=[...nodes]
        console.log("bb",bb)
        var  aa=[]
        this.echartsData=[]
          aa=  Array.from(new Set(bb.map(item => JSON.stringify(item)))).map(item => JSON.parse(item));
        console.log("node", this.echartsData)
        aa.forEach((e) => {
          let index = Math.ceil(Math.random()*10);
          let color = () => {
            if (index%4===0) {
              return '#228B22'
            } else if (index%4===1) {
              return '	#DEB887'
            } else if (index%4===2) {
              return '#20B2AA'
            } else if (index%4===3) {
              return '#FFB6C1'
            }
            return '#87CEFA';
          }
       
          this.echartsData.push(
            {
            name: e.name,
            tooltip: {
                        formatter: '{b}<br/><p>'+e.info,
                    },
            // x: Math.random() * 100,
            // y: Math.random() * 100,
            // itemStyle: {
            //   color: color()
            // }
          }
        );
        })
     console.log("this.echartsData", this.echartsData)
        this.initEcharts();
      }).then(() => {
        session.close()
      });
    },

    search(){
       
        this.query(this.formInline.startNode);
    },
    onSubmit() {
      this.$refs.neo4jform.validate((valid) => {
        if (valid) {
          this.connect();
          const session = this.$neo4j.getSession();
          let cypher = `Merge (n:Person{name: '${this.formInline.startNode}'})
          Merge (m:Person{name: '${this.formInline.endNode}'}) Merge (n)-[r:${this.formInline.relationName}]->(m)`;
          session.run(cypher).then(() => {
            this.formInline = {
              startNode: '',
              endNode: '',
              relationName: ''
            };
            this.query();
          }).then(() => {
            session.close()
          });
        }
      })
    },
        connect() {
            return this.$neo4j.connect(this.protocol, this.host, this.port, this.username, this.password)
                .then(driver => {
                    // Update the context of your app
                })
        },
        driver() {
            // Get a driver instance
            return this.$neo4j.getDriver()
        },
        testQuery() {
            // Get a session from the driver
            const session = this.$neo4j.getSession()

            // Or you can just call this.$neo4j.run(cypher, params)
            session.run('MATCH (n) RETURN count(n) AS count')
                .then(res => {
                    console.log(res)
                })
                .then(() => {
                    session.close()
                })
        },
    

    initChart() {
      this.chart = echarts.init(this.$refs.echarts, 'macarons')
      console.log("mychar",this.chart)
      this.chart.setOption({
        backgroundColor: '#1a4377',
    tooltip: {},
    toolbox: {
        feature: {
            saveAsImage: {},
        },
    },
    series: [
        {
            type: 'graph',
            layout: 'force',
            force: {
                repulsion: 1500,
                edgeLength: 120,
                layoutAnimation: true,
            },
            symbolSize: 70,
            nodeScaleRatio: 1, //图标大小是否随鼠标滚动而变
            roam: true, //缩放
            draggable: true, //节点是否可以拖拽
            edgeSymbol: ['none', 'arrow'], //线2头标记
            label: {
                normal: {
                    show: true,
                    position: 'inside',
                    color: '#FFF',
                },
            },
            edgeLabel: {
                normal: {
                    show: true,
                    textStyle: {
                        fontSize: 12,
                        color: '#FFF',
                    },
                    formatter: '{c}',
                },
            },
            symbolKeepAspect: false,
            focusNodeAdjacency: false, // 指定的节点以及其所有邻接节点高亮
            itemStyle: {
                normal: {
                    borderColor: '#29ACFC',
                    borderWidth: 2,
                    shadowColor: '#29ACFC',
                    color: '#29ACFC',
                    curveness: 0.08,
                },
            },

            lineStyle: {
                normal: {
                    opacity: 0.9,
                    width: 2,
                    curveness: 0.15,
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            {
                                offset: 0,
                                color: '#FFF', // 0% 处的颜色
                            },
                            {
                                offset: 1,
                                color: '#FFF', // 100% 处的颜色
                            },
                        ],
                        globalCoord: false,
                    },
                },
            },

            data:  [
                {
                    name: '李富贵',
                    tooltip: {
                        formatter: '{b} <br/>性别：男<br/>职务：富阳区灵桥镇灵桥村务农',
                    },
                    itemStyle: {
                        normal: {
                            color: '#FCBB5B',
                            borderColor: '#FCBB5B',
                            shadowColor: '#FCBB5B',
                        },
                    },
                },
                {
                      tooltip: {
                        formatter: '{b} <br/>性别：男<br/>出生年月：19951114<br/>星座：处女座',
                    },
                    name: '王桂花',
                },
                {
                      tooltip: {
                        formatter: '{b} <br/>性别：男<br/>出生年月：19951114<br/>星座：处女座',
                    },
                    name: '李思思',
                },
                {
                    name: '自住房屋',
                },
                {
                    name: '车子',
                },
                {
                    name: '租房',
                },
                {
                    name: '黄涛',
                },
                {
                    name: '于海',
                },
                {
                    name: '张柏',
                },
                {
                    name: '付梦杰',
                },
            ],
            links: [
                {
                    source: 0,
                    target: 1,
                    value: '夫妻',
                },
                {
                    source: 0,
                    target: 2,
                    value: '父亲',
                },
                {
                    source: 2,
                    target: 0,
                    value: '女儿',
                },
                {
                    source: 0,
                    target: 3,
                    value: '自住',
                },
                {
                    source: 0,
                    target: 4,
                    value: '车主',
                },
                {
                    source: 0,
                    target: 5,
                    value: '租户',
                },
                {
                    source: 5,
                    target: 6,
                    value: '租赁',
                },
                {
                    source: 5,
                    target: 7,
                    value: '租赁',
                },
                {
                    source: 5,
                    target: 8,
                    value: '租赁',
                },
                {
                    source: 5,
                    target: 9,
                    value: '租赁',
                },
            ],
        },
    ]
    })
  
}}}
</script>

<style scoped lang="css">
.neo4jMain {
  height: 100%;
  display: flex;
  flex-direction: column;
 
}
.neo4jMain .addContent {
    padding: 15px;
    box-shadow: -10px 0 10px #D3D3D3, /*左边阴影*/ 10px 0 10px #D3D3D3, /*右边阴影*/
      0 -10px 10px #D3D3D3, /*顶部阴影*/ 0 10px 10px #D3D3D3;
  }
 
  .neo4jMain .echarts {
    background-color: #333;
    flex: 1;
    flex-grow: 1;
    
  }
</style>
